#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define SIZE 1024
#define MAX_N 64

char* argv[MAX_N];

char pwd[SIZE];

const char* UserName()
{
    const char* username = getenv("USER");
    if(username) return username;
    else return "None";
}

const char* HostName()
{
    const char* hostname = getenv("HOSTNAME");
    if(hostname) return hostname;
    else return "Node";
}

const char* CurrentWorkDir()
{
    const char* pwd = getenv("PWD");
    if(pwd) return pwd;
    else return "None";
}

void Interactive(char str[])
{
    printf("[%s@%s %s]$ ", UserName(), HostName(), CurrentWorkDir());
    fgets(str, SIZE, stdin);
    str[strlen(str) - 1] = '\0';
}

void Split(char str[])
{

    int i = 0;
    argv[i++] = strtok(str, " ");
    while(argv[i++] = strtok(NULL, " "));
}

void Execute()
{
    pid_t id = fork();
    if(id == 0)
    {
        execvp(argv[0], argv);
        exit(0);
    }
    waitpid(id, NULL, 0);
}

int Bulidincmd()
{
    int ret = 0;
    if(strcmp("cd", argv[0]) == 0)
    {
        ret = 1;
        char *path = argv[1];
        if(!path) path = getenv("HOME");

        chdir(path);

        char tmp[SIZE];
        getcwd(tmp, SIZE);
        snprintf(pwd, SIZE, "PWD=%s", tmp);
        putenv(pwd);
        
    }
    return ret;
}

int main()
{
    while(1)
    {
        //输出命令行字符串，接受用户输入
        char str[SIZE];
        Interactive(str);
        int n = strlen(str);
        if(n == 0) continue;
        //分割字符串
        Split(str);

        n = Bulidincmd();
        if(n == 1) continue;
        //执行
        Execute();
    }
    // printf("%s", str);
    return 0;
}
